package com.lb.tools.lbtools.tools.file;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created with IntelliJ IDEA.
 * Description: ftp上传工具
 * User: liubin
 * Date: 2017-12-06
 * Time: 下午 2:45
 * @author 001030
 */
public class FtpUtil {

    public static boolean uploadFile(String url, String port, String username, String password, String path,
                                     String filename, InputStream input) {
        boolean returnValue = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            int portNO = Integer.parseInt(port);
            ftp.connect(url, portNO);// 连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return returnValue;
            }

            ftp.changeWorkingDirectory(path);
            //ftp默认上传文本格式，上传图片需要设置，否则图片失真
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.storeFile(filename, input);
            input.close();
            ftp.logout();
            returnValue = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return returnValue;
    }
}
